use shq_common::prelude::get_my_pool;

use crate::{config::get_workflow_newest_config, executor::is_can_create_flow};

pub (super) async fn create_flow_run(wfid:u32,user_id:u32)->anyhow::Result<u64>{
    let (conf,version)=get_workflow_newest_config(wfid).ok_or(anyhow::anyhow!("wfid:{wfid} 在配置中不存在"))?;
    let is_can=is_can_create_flow(conf,user_id).await?;
    if !is_can{
        return Err(anyhow::anyhow!("用户没有权限创建该流程"));
    }
    let mut tx=get_my_pool().begin().await?;
    let sql="insert into flow_run (wfid,version,step_id,create_time,state) values (?,?,1,now(),0)";
    let res=sqlx::query(sql).bind(wfid).bind(version).execute(&mut *tx).await?;
    let run_id=res.last_insert_id();
    let sql="insert into flow_run_step (run_id,step_id,emid,start_time,state) values (?,1,?,now(),1)";
    sqlx::query(sql).bind(run_id).bind(user_id).execute(&mut *tx).await?;
    tx.commit().await?;
    Ok(run_id)
}
pub (super) async fn flow_to_step(run_id:u64,step_id:u8,tx:&mut sqlx::Transaction<'_, sqlx::MySql>)->anyhow::Result<()>{
    let sql="update flow_run set state=0,step_id=? where run_id=?";
    let tx: &mut sqlx::MySqlConnection = tx;
    sqlx::query(sql).bind(step_id).bind(run_id).execute(tx).await?;
    Ok(())
}
pub (super) async fn flow_finish(run_id:u64,step_id:u8,tx:&mut sqlx::Transaction<'_, sqlx::MySql>)->anyhow::Result<()>{
    let sql="update flow_run set state=1,step_id=? where run_id=?";
    let tx: &mut sqlx::MySqlConnection = tx;
    sqlx::query(sql).bind(step_id).bind(run_id).execute(tx).await?;
    Ok(())
}
pub (super) async fn flow_suspend(run_id:u64,tx:&mut sqlx::Transaction<'_, sqlx::MySql>)->anyhow::Result<()>{
    let sql="update flow_run set state=2 where run_id=?";
    let tx: &mut sqlx::MySqlConnection = tx;
    sqlx::query(sql).bind(run_id).execute(tx).await?;
    Ok(())
}
pub (super) async fn flow_activate(run_id:u64,tx:&mut sqlx::Transaction<'_, sqlx::MySql>)->anyhow::Result<()>{
    let sql="update flow_run set state=0 where run_id=?";
    let tx: &mut sqlx::MySqlConnection = tx;
    sqlx::query(sql).bind(run_id).execute(tx).await?;
    Ok(())
}
